package com.ssh.call;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class BlockedMutex {
	private Lock lock = new ReentrantLock();

	public BlockedMutex() {
		// Acquire it right away, to demonstrate interruption
		// of a task blocked on a ReentrantLock:
		System.out.println("--turned block lock constructor..");
		lock.lock();
		System.out.println("--reurns from construtor..");
		// lock.unlock();
	}

	public void f() {
		// This will never be available to a second task
		System.out.println("--turned to f()");
		try {
			lock.lockInterruptibly();
			System.out.println("----正式执行内容---");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("-------------------------");
		} // Special call

		// boolean flag = lock.tryLock();
		// boolean flag = false;
		// try {
		// flag = lock.tryLock(1, TimeUnit.SECONDS);
		// } catch (InterruptedException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// System.out.println(flag == true ? "获得锁" : "没有获得锁");
		System.out.println("lock acquired in f()--执行最后一句");
	}
}

class Blocked2 implements Runnable {
	BlockedMutex blocked = new BlockedMutex();

	public void run() {
		System.out.println("Waiting for f() in BlockedMutex");
		blocked.f();
		System.out.println("Broken out of blocked call");
	}
}

public class Interrupting2 {
	public static void main(String[] args) throws Exception {
		Thread t = new Thread(new Blocked2());
		t.start();
		TimeUnit.SECONDS.sleep(1);
		System.out.println("Issuing t.interrupt()");
		t.interrupt();
	}
}